<template>
  <el-tabs type="border-card">
    <el-tab-pane label="商品基本信息">
      <el-form :model="dataForm" ref="ruleForm" label-width="150px" class="demo-ruleForm">
        {{dataForm.goods}}
        <h3>---------------------------------------------------------------------------</h3>
        {{dataForm.goodsDesc}}
        <h3>---------------------------------------------------------------------------</h3>
        {{dataForm.items}}
        <el-form-item label="商品分类">
          <el-select v-model="dataForm.goods.category1Id" placeholder="请选择一级分类" style="width:27%">
            <el-option
              v-for="item in categorys1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category2Id" placeholder="请选择二级分类" style="width:27%">
            <el-option
              v-for="item in categorys2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category3Id" placeholder="请选择三级分类" style="width:27%">
            <el-option
              v-for="item in categorys3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          {{dataForm.goods.typeTemplateId}}
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="dataForm.goods.goodsName" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="dataForm.goods.brandId" placeholder="请选择品牌" style="width:81%">
            <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="dataForm.goods.caption" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="dataForm.goods.price" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍">
          <el-input type="textarea" v-model="dataForm.goodsDesc.introduction" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="包装列表">
          <el-input type="text" v-model="dataForm.goodsDesc.packageList" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="售后服务">
          <el-input type="text" v-model="dataForm.goodsDesc.saleService" style="width:81%"></el-input>
        </el-form-item>
      </el-form>
    </el-tab-pane>

    <el-tab-pane label="商品图片">
      <el-button type="warning" @click="newPic" plain size="mini">新建</el-button>
      <el-table
        :data="dataForm.goodsDesc.itemImages"
        style="width: 100%">
        <el-table-column
          prop="color"
          label="颜色"
          align="center">
        </el-table-column>
        <el-table-column
          align="center"
          label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100" height="100">
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="dataForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>

    <el-tab-pane label="扩展属性">
      <el-form label-width="150px" class="demo-ruleForm">
        <el-form-item :label="cust.text" v-for="(cust,index) in dataForm.goodsDesc.customAttributeItems" :key="index">
          <el-input type="text" v-model="cust.value" style="width:81%"></el-input>
        </el-form-item>
      </el-form>
    </el-tab-pane>

    <el-tab-pane label="规格">
      <el-table
        :data="specificationItems"
        style="width: 100%">
        <el-table-column
          width="100">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-checkbox-group v-model="optionList[scope.$index]" size="mini" @change="getOptionList(scope.row.text)">
              <el-checkbox :label="option.optionName" v-for="option in scope.row.options" :key="option.id" border ></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
      <!--sku商品列表-->
      <el-table
        :data="dataForm.items"
        style="width: 100%">
        <el-table-column
          v-for="(spec,key) in dataForm.goodsDesc.specificationItems"
          :label="spec.attributeName"
          align="center"
          :key="key">
          <template slot-scope="scope">
            {{scope.row.spec[spec.attributeName]}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="价格">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="数量">
          <template slot-scope="scope">
            <el-input v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>

    <el-button type="primary" @click="save()"  size="small" icon="el-icon-edit-outline" style="margin-top: 10px;">保存</el-button>
    <el-button type="warning"  size="small" icon="el-icon-share">返回列表</el-button>

    <el-dialog title="上传商品图片" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="imageEntity">
        {{imageEntity}}
        <el-form-item label="颜色" label-width="100px">
          <el-input v-model="imageEntity.color" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" label-width="100px">
          <el-upload
            drag
            class="upload-demo"
            :file-list="fileList"
            :http-request="uploadFile"
            action=""
            list-type="picture">
            <!--<el-button size="small" type="primary">点击上传</el-button>-->
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPic">确 定</el-button>
      </div>
    </el-dialog>
  </el-tabs>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        goods: {typeTemplateId: '',brandId: ''},      // spu
        goodsDesc: {itemImages: [], customAttributeItems: [], specificationItems: []},  // spu商品描述
        items: []                         // sku列表
      },
      dialogFormVisible: false, // 对话框是否显示的变量
      dataRule: {},
      categorys1: [],           // 一级分类
      categorys2: [],           // 二级分类
      categorys3: [],           // 三级分类
      brands: [],               // 品牌列表

      imageEntity: {},          // 当前上传的图片
      fileList: [],             // 上传的图片列表

      specificationItems:[],    // 代表规格及规格选项列表
      optionList:[],            // 选中的规格的值数组
      specNames:[],             // 选中的规格名字数组
    }
  },
  created() {
    //1. 查询出一级分类
    this.findCategorys1()
    // this.find11();
    let id = this.$route.query.id
    console.log("id:",id)
  },
  computed: {
    //1. 如果一级分类的值发生变化，此时变量category1Idnew会重新计算,此时可以使用watch来监控这个值的变化
    // category1Idnew() {
    //   return this.dataForm.goods.category1Id;
    // },
    //2. 如果二级分类的值发生变化，此时变量category2Idnew会重新计算,此时可以使用watch来监控这个值的变化
    // category2Idnew() {
    //   return this.dataForm.goods.category2Id;
    // },
    //2. 如果三级分类的值发生变化，此时变量category2Idnew会重新计算,此时可以使用watch来监控这个值的变化
    // category3Idnew() {
    //   return this.dataForm.goods.category3Id;
    // },
  },
  watch: {
    //1. 当category1Id的值发生变化时，会加载二级分类
    'dataForm.goods.category1Id'(newV, oldV){      // newV：代表最后选择的一级分类id
      if(newV){
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys2 = data.list
            console.log("data:", data)
          } else {
            this.categorys2 = []
          }
        })
      }
    },
    //2. 当category1Id的值发生变化时，会加载三级分类
    'dataForm.goods.category2Id'(newV, oldV) {      // newV：代表最后选择的一级分类id
      if (newV){
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys3 = data.list
            console.log("data:", data)
          } else {
            this.categorys3 = []
          }
        })
      }
    },
    //3. 当category3Id的值发生变化时，会导致模板id的值发生变化
    'dataForm.goods.category3Id'(newV, oldV) {      // newV：代表最后选择的一级分类id
      if (newV) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/info/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm.goods.typeTemplateId = data.itemCat.typeId
          }
        })
      }
    },
    //4. 当dataForm.goods.typeTemplateId的值发生变化时，会做如下几件事情：
    // ① 导致品牌列表发生变化，更新品牌列表
    // ② 扩展属性列表发生变化。
    // ③ 规格列表发生变化。
    'dataForm.goods.typeTemplateId'(newV,oldV){   // newV: 代表新的模板id值
      if (newV){
        //4.1 查询品牌列表
        this.$http({
          url: this.$http.adornUrl(`/shop/typetemplate/info/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            //得到品牌列表
            this.brands = JSON.parse(data.typeTemplate.brandIds)
            //得到自定义扩展属性列表
            if (!this.$route.query.id){
              this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
            }
            //4.2 根据模板查询规格列表
            this.$http({
              url: this.$http.adornUrl(`/shop/specification/findSpecList/${newV}`),
              method: 'get',
            }).then(({data}) => {
              if (data && data.code === 0) {
                // console.log("spec-data:",data)
                this.specificationItems = data.list;
                // this.optionList这个变量代表用户点击并勾选了规格选项值后的数组，它是一个二维数组，其中二维数组的长度个数由规格的个数值决定。
                data.list.forEach(r=>{
                  this.optionList.push([])        // 为规格选项赋值
                  this.specNames.push(r.text);    // 为规格名称数组赋值
                } )
              }
            })
          }
        })
      }
    },
    //路由监听，当路由跳转到商品添加页面时，刷新页面根据商品id获得数据
    '$route' (to) {
      console.log("跳转目标页面",to)
      if (to.name === 'shop-goods-add'){
        this.findd();
      }
    }
  },
  methods: {
    //1. 查询出一级分类
    findCategorys1() {
      this.$http({
        url: this.$http.adornUrl('/shop/itemcat/findByParentId/0'),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.categorys1 = data.list
          // console.log("data:", data)
        } else {
          this.categorys1 = []
        }
      })
    },
    //2. 完成文件上传
    uploadFile(v){
      //2.1 定义表单数据
      let data = new FormData();
      data.append("file",v.file)      // 添加文件对象
      //2.2 清空文件列表
      this.fileList = [];
      //2.3 开始文件上传
      this.$http({
        url: this.$http.adornUrl('/shop/upload'),
        method: 'post',
        data:data,
        headers:{'Content-Type': 'multipart/form-data' },

      }).then(({data}) => {
        if (data && data.code === 0) {
          // console.log("url:",data.url)
          this.fileList.push({"name":v.raw,'url':data.url})
          this.imageEntity.url = data.url
        }
      })
    },
    //3. 将上传的图片放到dataFrom.goodsDesc.itemImages下并关闭对话框
    addPic(){
      this.dataForm.goodsDesc.itemImages.push(this.imageEntity)
      this.dialogFormVisible = false
    },
    //4. 点击新建按钮
    newPic(){
      //4.1 打开对话框
      this.dialogFormVisible = true;
      //4.2 将上次上传的图片清空
      this.imageEntity = {}
      //4.3 清空文件列表
      this.fileList = []
    },
    //5. 获取规格选项的值
    getOptionList(v){

      // [{"attributeName":"网络制式","attributeValue":["移动3G","移动4G"]},
      //   {"attributeName":"屏幕尺寸","attributeValue":["6寸","5寸"]}]
      // console.log("getOptionList:",this.optionList);
      let specList = [];
      //5.1 遍历规格选项，为specificationItems赋值
      for (let i = 0;i < this.optionList.length;i++){
        specList.push({attributeName:this.specNames[i],attributeValue:this.optionList[i]})
      }
      //5.2 将当前规格列表specList赋值给this.dataForm.goodsDesc.specificationItems
      // 其中,当某个规格一个都未选中时的情况处理,使用过滤器处理一下
      this.dataForm.goodsDesc.specificationItems=specList.filter(f=>f.attributeValue.length > 0);

      //5.3 创建规格列表表格的数据
      this.createSpecList()
      console.log(specList)

    },
    // 6. 动态构造sku商品列表的数据
    createSpecList(){
      //1. 定义默认的sku商品列表
      this.dataForm.items = [{spec:{},price:0,num:9999,status:'0',isDefault:'0'}];  // spec: 代表规格，类似：{"机身内存":"128G","网络":"电信4G"}
      //2. 得到用户选择的规格列表
      let items = this.dataForm.goodsDesc.specificationItems;
      //3. 如果有值，就动态向this.dataForm.items中添加内容
      if(items && items.length > 0){
        items.forEach(item=>{
          this.dataForm.items = this.addColumn(this.dataForm.items,item.attributeName,item.attributeValue)
        })
      }
    },
    //7. 添加一条数据
    addColumn(items,attName,attValue){
      //7.1 定义一个临时存放规格的数组
      let spList = [];
      //7.2 遍历items向spList放数据
      items.forEach(item=>{
        attValue.forEach(value=>{
          //7.2.1 构造一个新行(深克隆完成)
          let newItem = JSON.parse(JSON.stringify(item));
          //7.2.2 为新行赋值
          newItem.spec[attName] = value
          //7.2.3 向新数组添加内容
          spList.push(newItem);
        })
      })
      return spList;
    },
    save(){
      //把json对象转变为json串
      //处理表中的数据
      this.dataForm.goodsDesc.specificationItems = JSON.stringify(this.dataForm.goodsDesc.specificationItems)
      this.dataForm.goodsDesc.customAttributeItems = JSON.stringify(this.dataForm.goodsDesc.customAttributeItems)
      this.dataForm.goodsDesc.itemImages = JSON.stringify(this.dataForm.goodsDesc.itemImages)
      //处理item表中的数据
      this.dataForm.items.forEach(item => {
        item.spec = JSON.stringify(item.spec)
      })
      //向后台发送请求，保存tb_goods,tb_goodsdesc,tb_item三张表的数据
      //得到路由中查询参数
      let id = this.$route.query.id
      //发送请求
      this.$http({
        url: this.$http.adornUrl(`/shop/goods/${id ? 'update' : 'save'}`),
        method: `${id ? 'put' : 'post'}`,
        data:this.dataForm
      }).then(({data}) => {
        if (data && data.code === 0) {    // 如果添加或修改成功，就恢复默认值
          this.dataForm = {goods:{typeTemplateId: ''},goodsDesc: {itemImages: [],customAttributeItems: [],specificationItems: []},items:[]}
          this.specificationItems = []
          this.optionList = []
          this.fileList = []
          this.specNames = []
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    findd() {
      if(this.$route.query.id){
        let id = this.$route.query.id
        console.log("要修改商品的id:" , id)
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/FindById/${id}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            //设置各个属性的值
            this.dataForm = data.goods
            this.dataForm.goods.brandId = parseInt(data.goods.goods.brandId)
            this.dataForm.goodsDesc.itemImages = JSON.parse(this.dataForm.goodsDesc.itemImages)
            this.dataForm.goodsDesc.customAttributeItems = JSON.parse(this.dataForm.goodsDesc.customAttributeItems)
            this.dataForm.goodsDesc.specificationItems = JSON.parse(this.dataForm.goodsDesc.specificationItems)
            this.dataForm.items.forEach(item=>{
              item.spec=JSON.parse(item.spec)
            })
            //设置规格的值
            this.optionList = []
            this.dataForm.goodsDesc.specificationItems.forEach(spec=>{
              this.optionList.push(spec.attributeValue)
            })
          }
        })
      }
    }
  }
}
</script>
